package com.ipudong.widget;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;

public class OnSizeChangedLinearLayout extends LinearLayout {

    private final String tag = getClass().getSimpleName();
    private final int MIN_INTERVAL_HEIGHT = 50;
    private final Handler handler = new Handler();

    public OnSizeChangedLinearLayout(Context context) {
        super(context);
    }

    public OnSizeChangedLinearLayout(Context context, AttributeSet attr) {
        super(context, attr);
    }

    @Override
    protected void onSizeChanged(int w, final int h, int oldw, final int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.d(tag, String.format("w = %d, h = %d, oldw = %d, oldh = %d", w, h, oldw, oldh));
        handler.post(new Runnable() {
            @Override
            public void run() {
                int intervalHeight = oldh - h;
                Log.d(tag, "interval height = " + intervalHeight);
                boolean visible;
                visible = intervalHeight > MIN_INTERVAL_HEIGHT;
                Log.d(tag, "keyboard visible state:" + visible);
                if (getOnKeyboardStateChangeListener() != null) {
                    getOnKeyboardStateChangeListener().onStateChanged(visible);
                }
            }
        });
    }

    private OnKeyboardStateChangeListener onKeyboardStateChangeListener;

    private OnKeyboardStateChangeListener getOnKeyboardStateChangeListener() {
        return onKeyboardStateChangeListener;
    }

    public void setOnKeyboardStateChangeListener(OnKeyboardStateChangeListener onKeyboardStateChangeListener) {
        this.onKeyboardStateChangeListener = onKeyboardStateChangeListener;
    }

    public interface OnKeyboardStateChangeListener {
        void onStateChanged(boolean visible);
    }

}
